var wetter = {
  
  load: function () {
    if (!GBrowserIsCompatible()) {
      document.getElementWithId('map').innerHTML = 
        ('<p style="color:red">Google Maps does not support this browser.</p>');
      return;
    }

    var MAP_TYPES = [G_PHYSICAL_MAP].concat(G_DEFAULT_MAP_TYPES);
    var MAP_TYPES_BY_ARG = {};

    for (var i in MAP_TYPES) {
      var mapType = MAP_TYPES[i];
      MAP_TYPES_BY_ARG[mapType.getUrlArg()] = mapType;
    }

    var urlParams = this.getUrlParams(document.URL);
    var center = this.parseLatLng(urlParams.ll, 51.206883, 8.4375);
    var zoom = this.parseInt(urlParams.z, 6);
    var mapType = MAP_TYPES_BY_ARG[urlParams.t || 'm'];

    var map = this.map = new GMap2(document.getElementById("map"));
    map.setCenter(center, zoom, mapType);
    map.enableGoogleBar();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();

    map.addMapType(G_PHYSICAL_MAP);
    map.addControl(new GLargeMapControl());

    this.radarControl = new wetter.RadarControl()
    map.addControl(this.radarControl);
    map.addControl(new wetter.LinkControl());

    var mapControl = new GHierarchicalMapTypeControl();
    map.addControl(mapControl);

    this.updateOverlays();
  },
  
  unload: function() {
    delete this.radarControl;
    delete this.overlays;
    delete this.map;
    GUnload();
  },

  getUrlParams: function(url) {
        var params = url.split('#')[0].split('?').pop().split('&');
    var dict = {};
 
    for (var i in params) {
      var param = params[i].split('=');
      dict[param[0]] = param[1];
    }

    return dict;
  },

  parseInt: function(i, defValue) {
    try { if (i) return parseInt(i); } catch (e) {}
    return defValue;
  },

  parseFloat: function(f, defValue) {
    try { if (f) return parseFloat(f); } catch (e) {}
    return defValue;
  },

  parseLatLng: function(ll, defaultLat, defaultLng) {
    var fs = ll ? ll.split(',') : [];
    return new GLatLng(
      fs.length > 0 ? this.parseFloat(fs[0], defaultLat) : defaultLat, 
      fs.length > 1 ? this.parseFloat(fs[1], defaultLng) : defaultLng);
  },

  updateOverlays: function() {
    this.radarControl.setText('loading ...');
    this.sendRequest('/wetter/radarOverlays', this.onupdate);
  },

  setOverlays: function(overlays, maxAge) {
    var oldOverlays = this.overlays || [];
    var o = overlays[overlays.length-1];

    if (oldOverlays.length != 0 && oldOverlays[0].radar.href == o.href) {
      this.radarControl.setText(o.name + ' {' + maxAge + '}');
      return;
    }

    this.overlays = [];

    for (var i=overlays.length; i > 0;) {
      var o = overlays[--i];
      var overlay = new GGroundOverlay(o.href, new GLatLngBounds(
        new GLatLng(o.south, o.west), new GLatLng(o.north, o.east)));

      overlay.radar = o;

      if (this.overlays.length == 0) {
        this.map.addOverlay(overlay);
        this.radarControl.setText(o.name + ' [' + maxAge + ']');
        o.added = true;
      }

      this.overlays.push(overlay);
    }
    
    for (var i in oldOverlays) {
      var o = oldOverlays[i];
      if (o.radar.added) this.map.removeOverlay(o);
      delete o.radar;
    }
  },

  onupdate: function(request) {
    var cacheControl = request.getResponseHeader('Cache-Control');
    var maxAge = wetter.parseCacheControl(cacheControl);

    if (request.status != 200 || !request.responseText || request.responseText.length < 4) {
      wetter.radarControl.setText('update failed');
    }
    else {
      var response = eval(request.responseText.substr(3));

      if (response.length != 0) {
        wetter.setOverlays(response, maxAge);
      }
    }

    window.setTimeout("wetter.updateOverlays()", 1000 * maxAge);
  },

  parseCacheControl: function(cacheControl) {
    if (cacheControl && cacheControl.indexOf('max-age=') == 0) {
      maxAge = parseInt(cacheControl.substr(8));
      if (maxAge > 0) {
        return maxAge;
      }
    }

    return 30;
  },

  XMLHttpRequest: window.XMLHttpRequest || function() {
    var m = function (s) { return function() { return new ActiveXObject(s) }};
    var t = function (s) { var f=m(s), r=f(); wetter.XMLHttpRequest=f; return r };
    var a = ["Microsoft.XMLHTTP","Msxml2.XMLHTTP","MSXML2.XMLHTTP.3.0"];
    while (a.length!=0) try { return t(a.pop()) } catch (e) {};
    throw "Could not find an XMLHttpRequest alternative.";
  },
  
  sendRequest: function(url, fn, params) {
    var request = new wetter.XMLHttpRequest();
 
    if (typeof params != 'string' || params.length == 0) {
      request.open("GET", url, true);
    }
    else {
      request.open("POST", url, true);
      request.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded"); 
      request.setRequestHeader("Content-Length", params.length);
    }
    
    request.onreadystatechange = function() {
      if (wetter && request.readyState == 4) fn(request);
    };
      
    request.send(params);  
  }

};


wetter.RadarControl = function() {
};

wetter.RadarControl.prototype = new GControl(true, false);

wetter.RadarControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.className = "radarControl";
  var p = document.createElement("p");
  this.textNode = this.textNode || document.createTextNode("loading radar ...");
  p.appendChild(this.textNode);
  container.appendChild(p);
  map.getContainer().appendChild(container);
  return container;
};

wetter.RadarControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100,7));
};

wetter.RadarControl.prototype.setText = function(text) {
  if (!this.textNode) document.createTextNode(text);
  this.textNode.data = text;
};


wetter.LinkControl = function() {
};

wetter.LinkControl.prototype = new GControl(true, false);

wetter.LinkControl.prototype.initialize = function(map) {
  var link = document.createElement("a");
  var updater = function() {
    link.href = '?ll=' + map.getCenter().toUrlValue() +
      '&z=' + map.getZoom() +
      '&t=' + map.getCurrentMapType().getUrlArg();
  }

  updater();

  GEvent.addListener(map, "load", updater);
  GEvent.addListener(map, "moveend", updater);
  GEvent.addListener(map, "dragend", updater);
  GEvent.addListener(map, "zoomend", updater);
  GEvent.addListener(map, "maptypechanged", updater);

  var container = document.createElement("div");
  container.className = "radarControl";
  var p = document.createElement("p");

  link.className = "radarLink";
  link.appendChild(document.createTextNode("Link"));

  p.appendChild(link);
  container.appendChild(p);
  map.getContainer().appendChild(container);

  return container;
};

wetter.LinkControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(400,7));
};







/*
 map.addOverlay(whatever);
    map.getPane(1).lastChild.id="yourdaddy"

....

    var div=document.getElementById("yourdaddy");

// For FF & others

    div.style.opacity=whatever;

// For IE

    div.filters.alpha.opacity=Math.round(100*whatever);

For IE, you will have to prime the pump with:

    div.style.filter="alpha(opacity=100)";

Otherwise, "div.filters" will be undefined.

I believe "div.style.MozOpacity" is now obsolete. 

*/